Dictionaries¶

🎨 {}¶

In [15]:
meals = {
    'breakfast': 'oatmeal',
    'lunch': 'leftovers',
    'dinner': 'spaghetti'
}

NOTES

  • curly braces, colons, commas
  • key-value pairs
  • this is a dictionary or dict
In [16]:
type(meals)
Out[16]:
dict
In [17]:
meals
Out[17]:
{'breakfast': 'oatmeal', 'lunch': 'leftovers', 'dinner': 'spaghetti'}
In [18]:
meals['breakfast']
Out[18]:
'oatmeal'

NOTES

  • What is this going to print?
  • square brackets for item lookup
  • you provide the key and you get the associated value back
In [19]:
meals['lunch']
Out[19]:
'leftovers'
In [20]:
meals['leftovers']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[20], line 1
----> 1 meals['leftovers']

KeyError: 'leftovers'

NOTES

  • You can only lookup by keys, not by values
  • When you try to lookup a key that is not in the dictionary, you get a KeyError
In [21]:
meals = {
    'breakfast': 'candy',
    'lunch': 'pizza',
    'breakfast': 'oatmeal',
    'dinner': 'sandwiches',
    'breakfast': 'wheaties'
}
In [22]:
meals
Out[22]:
{'breakfast': 'wheaties', 'lunch': 'pizza', 'dinner': 'sandwiches'}

NOTES

  • You can't have duplicate keys
  • If you assign to the same key again, the new value overwrites the old value
In [23]:
meals['lunch'] = 'salad'
In [24]:
meals
Out[24]:
{'breakfast': 'wheaties', 'lunch': 'salad', 'dinner': 'sandwiches'}
In [25]:
meals['second breakfast'] = 'bagels'
In [26]:
meals
Out[26]:
{'breakfast': 'wheaties',
 'lunch': 'salad',
 'dinner': 'sandwiches',
 'second breakfast': 'bagels'}
In [27]:
for meal, offering in meals.items():
    print(f'For {meal} you get {offering}. 😋') 
For breakfast you get wheaties. 😋
For lunch you get salad. 😋
For dinner you get sandwiches. 😋
For second breakfast you get bagels. 😋
In [28]:
list(meals.items())
Out[28]:
[('breakfast', 'wheaties'),
 ('lunch', 'salad'),
 ('dinner', 'sandwiches'),
 ('second breakfast', 'bagels')]

NOTES

  • meals.items() returns a sequence of key-value pairs, which we unpack into meal and offering
In [29]:
for meal in meals: # iterate over keys
    print(meal)
breakfast
lunch
dinner
second breakfast
In [30]:
for dish in meals.values():  # iterate over values
    print(dish)
wheaties
salad
sandwiches
bagels

🖌 in + dict¶

In [31]:
hometowns = {
    'Dallin Oaks': 'Provo, UT',
    'Jeffery Holland': 'St George, UT',
    'Merril Bateman': 'Lehi, UT',
    'Cecil Samuelson': 'Salt Lake City, UT',
    'Kevin Worthen': 'Dragerton, UT',
    'Shane Reese': 'Logan, UT'
}

NOTES

  • we can use numbers as keys too, not just strings
In [36]:
'Shane Reese' in hometowns
Out[36]:
True
In [33]:
'Provo, UT' in hometowns
Out[33]:
False
In [34]:
'Karl Maeser' in hometowns
Out[34]:
False
In [37]:
for person in ['Kevin Worthen', 'Henry Eyring', 'Shane Reese', 'Ernest Wilkinson', 'Karl Maeser']:
    if person in hometowns:
        print(f'{person} was born in {hometowns[person]}.')
    else:
        print(f"I don't know where {person} was born.")
Kevin Worthen was born in Dragerton, UT.
I don't know where Henry Eyring was born.
Shane Reese was born in Logan, UT.
I don't know where Ernest Wilkinson was born.
I don't know where Karl Maeser was born.

NOTES

  • We saw earlier that asking for a key-value that doesn't exist in a dictionary gives us a KeyError
  • Use key in dict syntax to check that the key is present
    • and if it isn't, do something else

🧑🏽‍🎨 The world needs more emojis¶

You are given a dictionary mapping words to emojis.

Replace all instances of a word with it's corresponding emoji. Ignore case.

So, given a dictionary

emojis = {'dog': '🐶', 'cat': '🐱', 'tree': '🌳', 'bird': '🐦'}

The phrase

My dog has fleas.

Becomes

My 🐶 has fleas.
In [ ]:
! python for_class/emojis_solution.py "The Dogs chased the cat which chased the bird that sat in the tree in my yard."

🧑🏻‍🎨 Team Assignments¶

Community members want to register for the Rec Center sports teams.

You have a dictionary that maps age groups to team names.

Map a list of tuples containing a name and age to a list of tuples containing name and team.

To compute a participants age group, find the nearest multiple of 3 that is less than or equal to the participant age.

If the participant does not have an age-group assignment, they go in team "Old Fogies".

👨🏾‍🎨 Cipher¶

Given a dictionary mapping letters to other letters (called a "cipher"), encode a message.

Characters that are not in the cipher are preserved.

Extra credit: The cipher only contains lower-case letters, but you should encode upper-case letters also. Preserve casing.

Key Ideas¶

  • dict {}
  • Iterating over the key-value pairs in a dictionary
  • key in dict
  • Lookup information using []